package com.sdses.weather.model;

import cn.hutool.core.util.StrUtil;
import com.alibaba.ttl.TransmittableThreadLocal;
import com.sdses.weather.config.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

@Slf4j
public class RequestContextHolder {
    private static final ThreadLocal<RequestContext> CONTEXT_HOLDER = new TransmittableThreadLocal<>();

    public static void setContext(RequestContext context) {
        CONTEXT_HOLDER.set(context);
        // 同时设置 MDC
//        MDC.put("requestId", context.getRequestId());
//        MDC.put("weather", context.getWeather());
    }

    public static RequestContext getContext() {
        return CONTEXT_HOLDER.get();
    }

    public static void clear() {
        CONTEXT_HOLDER.remove();
        MDC.clear(); // 清理 MDC
    }

    // 供 SpEL 使用
    public static String getCacheKey() {
        RequestContext ctx = getContext();
        if (ctx == null) {
            log.error("系统异常 请稍后重试 找不到上下文");
            return "unknown_request:unknown";
        }
        String keyPrex = ctx.getCityId();
        if (StrUtil.isNotBlank(ctx.getLat()) && StrUtil.isNotBlank(ctx.getLon())) {
            keyPrex = ctx.getLat() + "-" + ctx.getLon();
        }

        return ctx.getProvider() + ':' + ctx.getType() + ':' + keyPrex;
    }

    public static int getTtl() {
        RequestContext ctx = getContext();
        if (ctx == null) {
            throw new BusinessException("系统异常 请稍后重试");
        }
        return ctx.getTtl();
    }


}